package com.base.component.ai.agent.utils;

import java.util.List;
import java.util.function.Consumer;

import org.springframework.util.CollectionUtils;

import com.base.component.ai.platform.core.converter.PromptResultConverterEditor;

public class PromptChatUtils {

    private static final String EMOJI_PATTERN = "[\\uD800\\uDC00-\\uDBFF\\uDFFF\\uD800-\\uDFFF]";
	
	public static String removeEmojii(String content) {
        return content.replaceAll(EMOJI_PATTERN, "");
    }

	public static String formatString(String content) {
		content=PromptResultConverterEditor.getData(content);
        return content.replace("{{", "{").replace("}}", "}");
    }
	
	public static String addExpansion(String content) {
        return content.replaceAll("\\{", "\\{{").replaceAll("\\}", "\\}}");
    }
	
	public static String getUri(String url) {
		if(url.startsWith("https")) {
			url=url.substring("https://".length());
			if(url.indexOf("?")!=-1) {
				return url.substring(url.indexOf("/")+1,url.indexOf("?"));
			}else {
				return url.substring(url.indexOf("/")+1);
			}
		}
		return url;
	}
	
	/**
     * 内容分句输出
     * @param sb 句子内容输出
     * @param frameConsumer 针对每个完整句子的处理
     */
    public static void handleTextFrame(StringBuilder sb,Consumer<String> frameConsumer) {
        List<String> curSends = PromptCharacterUtil.punctuation(sb.toString());
        if(CollectionUtils.isEmpty(curSends)) {
            //如果没有完整的句子，不需要处理
            return;
        }
        StringBuilder preSend = new StringBuilder();
        for(String s : curSends) {
            preSend.append(s);
            if(preSend.length() < 15) {
                // 如果单句少于15个字，不单独发，堆buffer，整合多句一起发。
            }else {
                String nowSend = preSend.toString();
                frameConsumer.accept(nowSend.toString());
                //句子输出了，清理掉buffer里的内容
                sb.delete(0, nowSend.length());
                preSend.delete(0, nowSend.length());
            }
        }
    }
	
}
